package com.hnkywl.jip.action;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.hnkywl.jip.dao.VoucherType;
import com.hnkywl.jip.interceptor.AuthInterceptor;
import com.hnkywl.jip.service.CompanyService;
import com.hnkywl.jip.service.InvoiceMergeService;
import com.hnkywl.jip.service.InvoiceVerifyService;
import com.hnkywl.jip.service.VoucherService;
import com.hnkywl.jip.utils.UUIDGenerator;
import com.hnkywl.jip.utils.VoucherItemData;
import com.hnkywl.jip.utils.XmlParse;
import net.ruixin.orm.hibernate.Page;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Type;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: jerry
 * Date: 13-2-25
 * Time: 下午8:43
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/invoice_merge")
public class InvoiceMergeAction extends SimpleActionSupport {
    private Integer id;
    private Integer status;
    private Integer attachment;

    private String operator;

    private Date startTime;

    private Date endTime;

    private Date systemDate;
    private String voucherItems;

    private Integer voucher;

    private Integer companyId;

    private Integer limit;
    private Integer start;

    private Page<Object[]> gridResult = new Page<Object[]>();

    private Map<String, Object> voucherMerge;

    private List<Object[]> companyList;
    private Map<String, String> result = new HashMap<String, String>();
    private Map userInfo;
    private List<Object[]> invoiceList;

    private XmlParse xmlParse;
    private VoucherService voucherService;
    private CompanyService companyService;
    private InvoiceMergeService invoiceMergeService;

    @Action("search")
    public String search() {
        endTime = new Date();
        startTime = new Date();
        startTime.setDate(1);
        companyList = companyService.searchAllCompany();
        return SUCCESS;
    }

    @Action("grid_json")
    public String gridJson() {
        gridResult = this.invoiceMergeService.findInvoiceMerge(startTime, endTime, status, companyId, voucher, operator, limit, start);
        return SUCCESS;
    }

    @Action("voucher_json")
    public String voucherJson() {
        systemDate = new Date();
        voucherMerge = this.invoiceMergeService.getVoucher(id, null,null);
        userInfo = (HashMap<String, Object>) this.session.get(AuthInterceptor.SESSION_KEY);
        try {
        Map<String, Object> voucherMaster = invoiceMergeService.getVoucherMaster(id, attachment, null, null, null, userInfo);
        voucherMerge.put("master", voucherMaster);
        result.put(XmlParse.RESPONSEFLAG, "1");
        result.put(XmlParse.RESPONSEMESSAGE, "获取成功!");
        } catch (Exception e) {
            e.printStackTrace();
            result.put(XmlParse.RESPONSEFLAG, "0");
            result.put(XmlParse.RESPONSEMESSAGE, e.getMessage());
        }
        return SUCCESS;
    }

    @Action(value = "generate_voucher_json",
            results = {@Result(name = "success", location = "/WEB-INF/content/invoice_verify/response_json.ftl")})
    public String generateVoucher() {
        try {
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
            Type type = new TypeToken<List<VoucherItemData>>() {
            }.getType();
            List<VoucherItemData> voucherItemDataList = gson.fromJson(voucherItems, type);
            String uuid = UUIDGenerator.getUUID();
            Integer year = GregorianCalendar.getInstance().get(Calendar.YEAR);
            Integer mouth = GregorianCalendar.getInstance().get(Calendar.MONTH);
            Boolean begin = voucherService.beginGenerateVoucher(id, VoucherType.INVOICE_VERIFY);
            userInfo = (HashMap<String, Object>) this.session.get(AuthInterceptor.SESSION_KEY);
            if (!begin)
                throw new RuntimeException("其他用户已经开始导入该凭证，请选择其他凭证进行导入!");
            //凭证分录
            voucherMerge = invoiceMergeService.getVoucher(id, uuid,voucherItemDataList);
            //凭证头
            Map<String, Object> msgheader = voucherService.getMsgHeader(userInfo);
            voucherMerge.put("msgheader", msgheader);
            //凭证主表信息
            Map<String, Object> voucherMaster =
                    invoiceMergeService.getVoucherMaster(id, attachment, uuid, year.toString(), mouth.toString(), userInfo);
            voucherMerge.put("master", voucherMaster);
            String r = voucherService.generateVoucher(voucherMerge);
            result = xmlParse.getContent(r);
            if ("1".equals(result.get(XmlParse.RESPONSEFLAG))) {
                String vchrid = result.get(XmlParse.VCHRID);
                String vchrnum = result.get(XmlParse.VCHRNUM);
                Boolean success = voucherService.generateVoucherSuccess(uuid, vchrid, vchrnum, year, id, VoucherType.INVOICE_VERIFY);
                if (!success)
                    throw new RuntimeException("凭证导入成功，但凭证信息回写失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put(XmlParse.RESPONSEFLAG, "0");
            result.put(XmlParse.RESPONSEMESSAGE, e.getMessage());
        }
        return SUCCESS;
    }

    @Action(value = "revoke_voucher_json",
            results = {@Result(name = "success", location = "/WEB-INF/content/invoice_verify/response_json.ftl")})
    public String revokeVoucher() {
        try {
            userInfo = (HashMap<String, Object>) this.session.get(AuthInterceptor.SESSION_KEY);
            voucherService.beginRevokeVoucher(id, VoucherType.INVOICE_MERGE);
            Map<String, Object> msgheader = voucherService.getMsgHeader(userInfo);
            Map<String, Object> revokeInfo = invoiceMergeService.getRevokeInfo(id);
            Map<String, Object> info = new HashMap<String, Object>();
            info.put("msgheader", msgheader);
            info.put("revokeinfo", revokeInfo);
            String r = voucherService.revokeVoucher(info);
            result = xmlParse.getContent(r);
            if ("1".equals(result.get(XmlParse.RESPONSEFLAG))) {
                voucherService.revokeVoucherSuccess(id, VoucherType.INVOICE_MERGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put(XmlParse.RESPONSEFLAG, "0");
            result.put(XmlParse.RESPONSEMESSAGE, e.getMessage());
        }
        return SUCCESS;
    }

    @Action(value = "rest_voucher_json",
            results = {@Result(name = "success", location = "/WEB-INF/content/invoice_merge/response_json.ftl")})
    public String restVoucher() {
        userInfo = (HashMap<String, Object>) this.session.get(AuthInterceptor.SESSION_KEY);
        Integer userId = (Integer) userInfo.get(AuthInterceptor.USER_ID_SESSION_KEY);
        String error = voucherService.restVoucher(userId, id, VoucherType.INVOICE_MERGE.getType());
        if (error != null) {
            result.put(XmlParse.RESPONSEFLAG, "0");
            result.put(XmlParse.RESPONSEMESSAGE, error);
        } else {
            result.put(XmlParse.RESPONSEFLAG, "1");
            result.put(XmlParse.RESPONSEMESSAGE, "重置成功!");
        }
        return SUCCESS;
    }

    @Action("invoice_merge_list")
    public String InvoiceMergeList() {
        invoiceList = invoiceMergeService.getInvoiceMerge(id);
        return SUCCESS;
    }

    //==================getter setter========================

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public Date getEndTime() {
        return endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }
    //==================getter========================

    public Date getSystemDate() {
        return systemDate;
    }

    public Page<Object[]> getGridResult() {
        return gridResult;
    }

    public Map<String, Object> getVoucherMerge() {
        return voucherMerge;
    }

    public List<Object[]> getCompanyList() {
        return companyList;
    }

    public Map<String, String> getResult() {
        return result;
    }

    public List<Object[]> getInvoiceList() {
        return invoiceList;
    }

    //==================setter========================
    public void setId(Integer id) {
        this.id = id;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public void setAttachment(Integer attachment) {
        this.attachment = attachment;
    }

    public void setOperator(String operator) {
        this.operator = operator;
    }

    public void setVoucher(Integer voucher) {
        this.voucher = voucher;
    }

    public void setCompanyId(Integer companyId) {
        this.companyId = companyId;
    }

    public void setLimit(Integer limit) {
        this.limit = limit;
    }

    public void setStart(Integer start) {
        this.start = start;
    }

    public void setVoucherItems(String voucherItems) {
        this.voucherItems = voucherItems;
    }

    @Autowired
    public void setInvoiceMergeService(InvoiceMergeService invoiceMergeService) {
        this.invoiceMergeService = invoiceMergeService;
    }

    @Autowired
    public void setVoucherService(VoucherService voucherService) {
        this.voucherService = voucherService;
    }

    @Autowired
    public void setXmlParse(XmlParse xmlParse) {
        this.xmlParse = xmlParse;
    }

    @Autowired
    public void setCompanyService(CompanyService companyService) {
        this.companyService = companyService;
    }
}
